package cmd

import (
	"fmt"
	"github.com/manifoldco/promptui"
	"github.com/spf13/cobra"
	"strings"
	"wdhcr-jvm-cli/utils"
)

type pepper struct {
	Name string
}

var listCmd = &cobra.Command{
	Use:   "ls",
	Short: "Check out the switchable version",
	Run: func(cmd *cobra.Command, args []string) {
		list()
	},
}

func init() {
	rootCmd.AddCommand(listCmd)
}

func list() {
	var peppers []pepper
	homeDir := utils.GetUserHome()
	dirs := utils.ReadDir(homeDir + "/.wjvm/jdk_package")
	jdkVersion := utils.GetDefaultJdkVersion()
	if len(dirs) <= 0 {
		peppers = append(peppers, pepper{Name: jdkVersion})
	} else {
		for _, fileName := range dirs {
			peppers = append(peppers, pepper{Name: strings.Replace(fileName, ".dmg", "", -1)})
		}
	}

	templates := &promptui.SelectTemplates{
		Label: "{{ . }}?",
		// 选中 图标 名称｜ 颜色  \U0001f139
		Active: "☃︎ {{ .Name | cyan }} ",
		// 未选中
		Inactive: "  {{ .Name | white }}",
		// 最终选中
		Selected: "☃︎ {{ .Name | red | cyan }}",
	}

	prompt := promptui.Select{
		Label:     "Please select the jdk version that needs to be switched",
		Items:     peppers,
		Templates: templates,
		Size:      4,
		// 当前选中项
		CursorPos: getDefaultJdkIndex(peppers),
	}

	i, _, err := prompt.Run()

	if err != nil {
		fmt.Printf("Prompt failed %v\n", err)
		return
	}

	fmt.Printf("You choose %s\n", peppers[i].Name)
	unInstallJdk(jdkVersion)
	installJdk(peppers[i].Name)

}

func installJdk(jdkOption string) {

	// 创建一个安装挂载目录
	// 用户目录下 创建一个 .wjvm 目录
	utils.ExecSh("mkdir ~/.wjvm/mountDir")

	// 将dmg 安装包挂载到 mountDir 文件上
	utils.ExecSh(fmt.Sprintf("hdiutil attach ~/.wjvm/jdk_package/%s.dmg -mountpoint ~/.wjvm/mountDir", jdkOption))
	// 执行pkg 安装包命令进行安装
	versionNum := strings.Replace(jdkOption, "zulu-", "", -1)
	versionNum = strings.Replace(versionNum, ".jdk", "", -1)
	sh, err := utils.ExecSh(fmt.Sprintf("sudo installer -pkg ~/.wjvm/mountDir/Double-Click\\ to\\ Install\\ Azul\\ Zulu\\ JDK\\ %s.pkg  -target /Library/Java/JavaVirtualMachines", versionNum))
	if err != nil {
		return
	}
	fmt.Println(sh)
	// 卸载挂载目录
	utils.ExecSh("hdiutil detach ~/.wjvm/mountDir")
	// 删除挂载目录
	utils.ExecSh("rm -rf ~/.wjvm/mountDir")
}

func unInstallJdk(jdkOption string) {
	utils.ExecSh("sudo rm -fr /Library/Internet\\ Plug-Ins/JavaAppletPlugin.plugin")
	utils.ExecSh("sudo rm -fr /Library/PreferencesPanes/JavaControlPanel.prefPane")
	utils.ExecSh("sudo rm -fr ~/Library/Application\\ Support/Java")
	_, err := utils.ExecSh(fmt.Sprintf("sudo rm -rf /Library/Java/JavaVirtualMachines/%s", jdkOption))
	if err != nil {
		fmt.Println(err)
	}
}

func getDefaultJdkIndex(peppers []pepper) int {
	version := utils.GetDefaultJdkVersion()
	for index, value := range peppers {
		if value.Name == version {
			return index
		}
	}
	return -1

}
